package cn.itlaobing.service.impl;

import java.text.ParseException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.itlaobing.dao.StudentDao;
import cn.itlaobing.entity.Student;
import cn.itlaobing.entity.enums.Gender;
import cn.itlaobing.service.StudentService;
import cn.itlaobing.vo.PageRequest;
import cn.itlaobing.vo.Pageable;

@Service
public class StudentServiceImpl implements StudentService {
	
	Log log = LogFactory.getLog(StudentServiceImpl.class);
	
	@Autowired
	private StudentDao studentDao;

	@Override
	public Student add(String name, String gender, String birthday) {
		try {
			Student student = new Student(name,Gender.valueOf(gender), DateUtils.parseDate(birthday, "yyyy-MM-dd"));
			studentDao.addStudent(student);
			log.info("添加成功"+student.getName());
			return student;
		} catch (ParseException e) {
			log.info(e);
			throw new RuntimeException();
		}
		
	}

	@Override
	public void delete(Long id) {
		studentDao.delete(Long.valueOf(id));
		log.info("删除成功"+id);
	}

	@Override
	public Student update(Long id, String name, String gender, String birthday) {
		Student student= studentDao.findById(Long.valueOf(id));
		if(student!=null){
			try {
				student.setName(name);
				student.setGender(Gender.valueOf(gender));
				student.setBirthday(DateUtils.parseDate(birthday, "yyyy-MM-dd"));
				studentDao.update(student);
				log.info("修改失败");
			} catch (ParseException e) {
				log.info(e);
				throw new RuntimeException();
			}
			
		}
		return student;
	}

	@Override
	public List<Student> findAll() {
		return studentDao.findAll();
	}

	@Override
	public Student findById(Long id) {
		return studentDao.findById(Long.valueOf(id));
	}

	@Override
	public Pageable<Student> findPageable(String pageNumber,String pageSize) {
		PageRequest pageRequest=new PageRequest();
		if(!StringUtils.isBlank(pageNumber)){//如果pageNumber不为空
			pageRequest.setPageNumber(Long.valueOf(pageNumber));
		}
		
		if(!StringUtils.isBlank(pageSize)){
			pageRequest.setPageSize(Long.valueOf(pageSize));
		}
		return studentDao.findPageable(pageRequest);
	}
	
	@Override
	public Pageable<Student> findPageable(PageRequest pageRequest) {
		return studentDao.findPageable(pageRequest);
	}
	
}
